import Vue from 'vue'

import Vuex from 'vuex'
Vue.use(Vuex)

//定义创建全局状态变量
const store = new Vuex.Store({
    state: {
        count: 100,
        tableData:[
            {id:1,name:'lxy',stat:true,money:11,count:3}, //33
            {id:2,name:'zx',stat:true,money:24,count:5}, //120
            {id:3,name:'sq',stat:false,money:16,count:1}
        ]
    },
    mutations: {    //修改变量的值，同步
        addCount(state, value) {
            state.count += value
        },
        subCount(state, value) {
            state.count -= value
        },
        setCount(state, value) {
            state.count = value
        }
    },
    actions:{   //修改变量的值，异步
        asyncAddCount(store){
            setTimeout(()=>{
                store.commit('addCount',1)
            },500)
        },
        asyncSubCount(store,value){
            setTimeout(()=>{
                store.commit('subCount',value)
            },500)
        }
    },
    //全局计算属性
    //getters概念：vuex身上的全局依赖，类似computed
    // getters依赖于state中原始数据的变化，并返回计算后的新数据
    getters:{
        totalPrice(state){
            return state.tableData.reduce((sum,obj)=> {
                if(obj.stat === true){
                    sum += obj.money * obj.count
                }
                return sum
            },0)
        }
    }
})

// 导出到main.js中注册到new Vue里

export default store